package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.util.KKutil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink13_Watermark_Allow_Late {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.setParallelism(1);

        env
                .socketTextStream("hadoop162", 9999)
                .map(line ->{
                    String[] strings = line.split(",");
                    return new WaterSensor(strings[0], Long.valueOf(strings[1]), Integer.valueOf(strings[2]));
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner( (element, ts) -> element.getTs())
                )
                .keyBy(WaterSensor::getId)
                // 窗口时间间隔5s，5s一个窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                    //设置允许元素延迟的时间。 超过指定时间到达水印之后的元素将被丢弃。 默认情况下，允许的延迟为0L 。
                //设置允许的延迟仅对事件时间窗口有效。
                .allowedLateness(Time.seconds(2))

                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String value, Context ctx, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        List<WaterSensor> list = KKutil.toList(elements);
                        out.collect(value+"  "+ elements);
                    }
                })
                .print();
        //两个执行结果，再次计算一次
/*      sensor_1  [WaterSensor(id=sensor_1, ts=2000, vc=10), WaterSensor(id=sensor_1, ts=4000, vc=30)]
        sensor_1  [WaterSensor(id=sensor_1, ts=2000, vc=10), WaterSensor(id=sensor_1, ts=4000, vc=30), WaterSensor(id=sensor_1, ts=3000, vc=20)]
* */

        env.execute();
    }



}
